package com.seagox.chat.auth.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.seagox.chat.common.ResultCode;
import com.seagox.chat.common.ResultData;
import com.seagox.chat.util.DocumentConverterUtils;
import com.seagox.chat.util.UploadUtils;

/**
 * 文件上传下载
 */
@RestController
@RequestMapping("/upload")
public class UploadController {
	
	@Value("${oss.endpoint}")
    private String endpoint;
	
	@Value("${oss.url}")
    private String ossUrl;
	
	@Autowired
    private UploadUtils uploadUtils;
	
	@Autowired
	private DocumentConverterUtils documentConverterUtils;

	/**
	 * 文件上传
	 */
	@PostMapping("/putObject/{bucketName}")
	public ResultData putObject(@RequestParam("file") MultipartFile file, @PathVariable String bucketName, Long companyId) {
		String address = uploadUtils.putObject(bucketName, file);
		if(StringUtils.isEmpty(address)) {
			return ResultData.warn(ResultCode.OTHER_ERROR, "文件服务器配置有误");
		} else {
			if(file.getContentType().contains("video")) {
				Map<String, Object> data = new HashMap<>();       
				data.put("url", address);
                data.put("width", 600);
                data.put("height", 400);
                data.put("poster", "");
                data.put("duration", 60);
				data.put("name", file.getOriginalFilename());
				data.put("format", file.getContentType());
				return ResultData.success(data);
			} else {
				return ResultData.success(address);
			}
		}
	}

	/**
	 * 下载文件
	 *
	 * @param response
	 */
	@PostMapping("/download")
	public void download(HttpServletResponse response, String url, String fileName) {
		url = url.replace(ossUrl, endpoint);
		OutputStream outputStream = null;
		InputStream inputStream = null;
		try {
			String prefix = fileName.substring(0, fileName.lastIndexOf("."));
			url = url.replace(prefix, URLEncoder.encode(prefix, StandardCharsets.UTF_8.toString()).replace("+", "%20"));
			System.out.println(url);
			response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName).getBytes("GBK"), "ISO-8859-1"));
			response.setContentType("application/octet-stream;charset=UTF-8");
			inputStream = new URL(url).openStream();
			outputStream = response.getOutputStream();
			IOUtils.copy(inputStream, outputStream);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	/**
     * 下载模版
     */
    @PostMapping("/downloadTemplate")
    public void downloadTemplate(HttpServletResponse response, String templateName) {
    	OutputStream outputStream = null;
        InputStream inputStream = null;
        try {
            response.setHeader("Content-Disposition", "attachment;filename=" + new String((templateName).getBytes("GBK"), "ISO-8859-1"));
            response.setContentType("application/octet-stream;charset=UTF-8");
            Resource resource = new ClassPathResource("\\template\\" + templateName);
            inputStream = resource.getInputStream();
            outputStream = response.getOutputStream();
            IOUtils.copy(inputStream, outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    /**
	 * 读取txt
	 */
	@PostMapping("/readTxt")
	public ResultData readTxt(String url) {
		url = url.replace(ossUrl, endpoint);
		InputStream inputStream = null;
		try {
			inputStream = new URL(urlEncode(url)).openStream();
			byte[] bytes = FileCopyUtils.copyToByteArray(inputStream);
			return ResultData.success(new String(bytes, StandardCharsets.UTF_8));
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
		return ResultData.error(ResultCode.INTERNAL_SERVER_ERROR);
	}
	
	/**
	 * 在线预览
	 *
	 * @param url      文件路径
	 * @param req      请求参数
	 * @return
	 */
	@GetMapping("/preview")
	public void preview(String url, HttpServletRequest req, HttpServletResponse response) throws IOException {
		url = url.replace(ossUrl, endpoint);
		OutputStream outputStream = null;
		InputStream inputStream = null;
		try {
			response.setHeader("Content-Disposition", "filename=" + new String(("preview.pdf").getBytes("GBK"), "ISO-8859-1"));
			response.setContentType("application/pdf");
			outputStream = response.getOutputStream();
			inputStream = new URL(urlEncode(url)).openStream();
			documentConverterUtils.convert(inputStream, outputStream);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (inputStream != null) {
				inputStream.close();
			}
			if (outputStream != null) {
				outputStream.close();
			}
		}
	}
	
	private static String urlEncode(String url){
	    try {
	        url = URLEncoder.encode(url, "UTF-8");
	        url = url.replaceAll("\\+", "%20");
	        url = url.replaceAll("%2F","/");
	        url = url.replaceAll("%3F","?");
	        url = url.replaceAll("%25","%");
	        url = url.replaceAll("%23","#");
	        url = url.replaceAll("%26","&");
	        url = url.replaceAll("%3D","=");
	        url = url.replaceAll("%3A",":");
	    } catch (UnsupportedEncodingException e) {
	        e.printStackTrace();
	    }
	    return url;
	}

}